<html>
<title>SammaAjiva</title>
<head>
<link rel="stylesheet" type="text/css" href="http://www.simulify.com/sammaAjiva/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="http://www.simulify.com/sammaAjiva/css/examples.css" />
  <style type="text/css">
     html, body { height: 96%; }
  </style>
<!-- GC -->
<!-- LIBS -->

<script type="text/javascript" src="http://www.simulify.com/sammaAjiva/ext-base.js"></script>
<!-- ENDLIBS -->
 <script type="text/javascript" src="http://www.simulify.com/sammaAjiva/ext-all.js"></script>

<!-- The key below is what has to be generated from the google map api site once for a site
    API - http://code.google.com/apis/maps/signup.html
 -->

<!--
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAApnt-zHm13A_xKOZfarNhjhT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSVnn93rBu-zJm_kcGh1tjfBtHixA" 
  type="text/javascript"></script>
  -->
  
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAApnt-zHm13A_xKOZfarNhjhS1UMIs-yNo38Xsrjc9Zqr-8VLbQRSwS_vr2cLdhyr5X8OkVDnx76e01w"
  type="text/javascript"></script>
</head>
<body onresize="resizeApp();" style="padding:0px;">

<!-- This is where map will be embeded-->
<div id="map" style="width:100%; height:100%;"></div> 

<script type="text/javascript">
//<![CDATA[

var map; // map object
var mapMarkers = []; // array to hold all Markers
var comparisons = []; // array to hold all the comparison strings

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
//API -  http://code.google.com/apis/maps/documentation/reference.html#GIcon
////// Start G O O G L E   C O D E //////////
var baseIcon = new GIcon();

//set the size here wqual to the size of the icon
baseIcon.iconSize = new GSize(32, 32);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);
////// end G O O G L E   C O D E //////////

/* Reading data from spreadsheet
*  1. Publish the spreadsheet. Check the continues update option and uncheck the only sammaajiva can see option.
*  2  Publish only the webdata worksheet 
*  3. The column headers should not be referance fields
*/

// Change these parameters to customize map


var worksheet_number = "1"; // this is the position of the worksheet

var param_styleSheetKey = "pa_90Ladph_R5UowztfmNZA";// this is key of the spreadsheet that you get when you publish it.


//MAPPING of the values needed here with Heading in the worksheet

// These variables contain the NAME of the column of the workSheet. NOT the DATA
// ***NOTE : The names of the columns as lowercased & spaces removed. So if you want to add a space 
// it is better if you use _ for that like "hall_lot" instead of "Hall Lot"
// 

var param_titleColumn = "name";

var param_tab1Column = "tab01";
var param_tab2Column = "tab02";
var param_tab3Column = "tab03";

var param_latColumn = "halllat";
var param_lngColumn = "halllong";

var param_zoomColumn = "zoom";
var param_icon1Column = "icon01";
var param_icon2Column = "icon02";

var param_comparisonColumn = "comparisonschedule";


/**
 * Loads map and calls function to load in worksheet data. This function is called whne browser loades the page.
 * this is from where the proceesing startes.
*/
function load() {
    if (GBrowserIsCompatible()) {
        // create the map by providing the id of the div in which you want the map to apear.
        map = new GMap2(document.getElementById("map"));

        // Add google map controls as needed. The list of controls and their details are at
        // API - http://code.google.com/apis/maps/documentation/controls.html
        // API - http://code.google.com/apis/maps/documentation/reference.html#GControlImpl
        
        map.addControl(new GLargeMapControl()); // adds the zoom control on the left
        map.addControl(new GMapTypeControl());  //
        map.addControl(new GOverviewMapControl()); // adds the small map overview in the lower right corner
        //map.addControl(new GScaleControl()); // adds the scale image
        
        
        // zoom levels are from 0-16
        var start_zoom_level = 2;
        var start_logitude =0;
        var start_latitude =0;
        // places  & zooms map as per these values
        map.setCenter(new GLatLng(start_latitude, start_logitude), start_zoom_level);

        
        map.enableDoubleClickZoom(); 
        map.enableScrollWheelZoom();        
        // this added the keyboard support to the map.
        // API - http://code.google.com/apis/maps/documentation/reference.html - search for GKeyboardHandler as it is not in the top links
        new GKeyboardHandler(map); 

        
        // call the resize function to set the map container size as per window size 
        resizeApp();  
        
        //Call to function which will get the data from the spreadsheet
        getJSON();
        
    } else {
        alert("Sorry, the Google Maps API is not compatible with this browser");
    } 
}

////// Start G O O G L E   C O D E //////////

/**
 * Function called when marker on the map is clicked.
 * Opens an info window (bubble) above the marker.
 * @param {Number} markerNum Number of marker in global array
 */
function markerClicked(markerNum) {
    var marker = mapMarkers[markerNum];
    GEvent.trigger(marker, "click");
}
////// End G O O G L E   C O D E //////////


/** 
 * This function is called once the data is received from spreadshee.
 * Iterates through worksheet rows - creating marker and tabs for each row.
 * @param {JSON} json Worksheet feed
 */       
function loadMapJSON(json) {
    // creat a rectangle
    // API - http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds
    var bounds = new GLatLngBounds();	  

    // calculate number of rows returned in the spreadsheet data.
    var no_of_centers = json.feed.entry.length;
    // chnage icons at which zoom level 0-16.
    var change_icon_on_zoom_level = 5; // a default value
    
    // loop through each row 
    for (var i = 0; i < no_of_centers; i++) {
          var entry = json.feed.entry[i];
          
          // These are the variables which will conatin the value for a column in the current row
          var lat = 0; // latitude
          var lng = 0; // logitude
          var label = ""; // label
          var tab1 = "";  // tab1 ontent
          var tab2 = "";  // tab2 content
          var tab3 = "";  // tab3 content
          var icon1 = ""; // icon1 url
          var icon2 = ""; // icon2 url
          var comparison = ""; // comparison string     

          // Check if data available then read it
          if(entry["gsx$" + param_latColumn]) {
             lat = parseFloat(entry["gsx$" + param_latColumn].$t);
          }      
          
          // Check if data available then read it
          if(entry["gsx$" + param_lngColumn]) {
             lng = parseFloat(entry["gsx$" + param_lngColumn].$t);
          }
          
          // Check if data available then read it  
          if(entry["gsx$"+param_titleColumn]) {
             label = entry["gsx$"+param_titleColumn].$t;
          }
          
          // Check if data available then read it
          if(entry["gsx$" + param_tab1Column]) {
              tab1 = entry["gsx$"+param_tab1Column].$t;
          }
          
          // Check if data available then read it
          if(entry["gsx$" + param_tab2Column]) {
              tab2 = entry["gsx$"+param_tab2Column].$t;
          }
          
          // Check if data available then read it
          if(entry["gsx$" + param_tab3Column]) {
              tab3 = entry["gsx$"+param_tab3Column].$t;
          }
          
          // Check if data available then read it
          if(entry["gsx$" + param_icon1Column]) {
              icon1 =    entry["gsx$" + param_icon1Column].$t;
          }
          
          // Check if data available then read it
          if(entry["gsx$" + param_icon2Column]) {
              icon2 =    entry["gsx$" + param_icon2Column].$t;
          }
          
          // Check if data available then read it         
          if(entry["gsx$" + param_comparisonColumn]) {
              comparison =    entry["gsx$" + param_comparisonColumn].$t;
          }
          
          // Check if data available then read it
          if(entry["gsx$" + param_zoomColumn]) {
              change_icon_on_zoom_level =    entry["gsx$" + param_zoomColumn].$t;
          }
          // this is to check if the value on latitude & logitude columns are ok. 
          // As in many cases they have been left empty or even text has been entered
          // which results in crash situation
          lat = lat || 0;
          lng = lng || 0;
          
          // creat the point where marker is to be created
          var point = new GLatLng(lat,lng);                        
    
          // create the marker
          var marker = createMarker(point, label, "Course Info", tab1, "Centre Info", tab2,"Travel Info", tab3,icon1, icon2,i);
          
          //add marker to map
          map.addOverlay(marker);
          
          // add marker to the array that we made for latter access
          mapMarkers.push(marker);
          
          // add the comprison string to comarison array. The value for comprison is read from this
          // when user presses the comprison button.
          comparisons.push(comparison);
          
          // add to bound object created
          bounds.extend(point);
    }
    
     // Add a function to the zoomend event. This gets fired when user zooms
     GEvent.addListener(map, "zoomend" ,function(){
        // get the current zoom level
        var curzoom =  map.getZoom();
        
        // Compare if the current zoom level is more than the zomm level specified in worksheet::zoom

        if(curzoom > change_icon_on_zoom_level){
            // go through all the markers and change the image of the icon to 
            // the url provided in worksheet::icon2
            for(var i=0;i<mapMarkers.length;i++){
                var marker = mapMarkers[i];
                marker.setImage(marker.getIcon().icon2);
            }
        }else{
            // go through all the markers and change the image of the icon to 
            // the url provided in worksheet::icon1
            for(var i=0;i<mapMarkers.length;i++){
                var marker = mapMarkers[i];
                marker.setImage(marker.getIcon().icon1);
            }
        }
    });
}

/**
 * Creates marker with ranked Icon or blank icon and Assigns onclick function.
 * @param {GLatLng} point = Point to create marker at
 * @param {String} title  = Tooltip title to display for marker
 * @param {String} lable1  = Text to show on the tab 1
 * @param {String} tab1    = Content to show in the tab 1
 * @param {String} lable2  = Text to show on the tab 2
 * @param {String} tab2    = Content to show in the tab 2
 * @param {String} lable3  = Text to show on the tab 3
 * @param {String} tab3    = Content to show in the tab 3
 * @param {Number} marker positon = number of the marker  being created. 
 *                                  E.g if there are 115 markers the first marker will have value 0 and last will have value 114
 * @return {GMarker} Marker created
 */
function createMarker(point, title, label1, tab1, label2, tab2,label3, tab3,icon1,icon2,position_of_marker) {
    
    // Creat a Icon and set it's image
    var nIcon = new GIcon(baseIcon);
    // default icons Just in case the icons have not been sent
    if(icon1.trim()==""){
        icon1 = "http://gmaps-samples.googlecode.com/svn/trunk/" + "markers/green/marker1.png";
    }
    
    // store the icon1 & icon2 urls for use when user zooms and the icon images is to be changed
    nIcon.icon1 = icon1;
    nIcon.icon2 = icon2;
    
    // set the image which is shown in icon.
    nIcon.image = nIcon.icon1; 
    
    // create a object for containing options that can be sent to creat a marker.
    //API - http://code.google.com/apis/maps/documentation/reference.html#GMarkerOptions
    var markerOpts = {};
    markerOpts.icon = nIcon;  // set the icon to the marker
    markerOpts.title = title; // set title which is seen when user mouseovers on the marker		 
    
    //create the marker
    // API - http://code.google.com/apis/maps/documentation/reference.html#GMarker
    var marker = new GMarker(point, markerOpts);
  
    // Add a function which gets called when user clicks on this marker
    GEvent.addListener(marker, "click", function() {
        // make the compare button
        var cmp = "<div><input type='button' value='Compare Centres in this region' onclick='compareWindow(" + position_of_marker + ");'/></div>";
        // add to content of tab1
        var tab1_cmp = cmp + tab1; 
        //create all 3 tabs
        //API - http://code.google.com/apis/maps/documentation/reference.html#GInfoWindowTab
        
        var tabs = [new GInfoWindowTab("Course Info", tab1_cmp), new GInfoWindowTab("Centre Info", tab2),new GInfoWindowTab("Travel Info", tab3)];
        //API - http://code.google.com/apis/maps/documentation/reference.html#GInfoWindowTab
        marker.openInfoWindowTabsHtml(tabs);

    });
    return marker;
}

/**
 * Creates a script tag in the page that loads in the 
 * JSON feed for the specified key/ID. 
 * Once loaded, it calls loadMapJSON.
 */
function getJSON() {
    // Retrieve the JSON feed and then call the function loadMapJSON with the data received from
    // the worksheet
    ////// Start G O O G L E   C O D E //////////
    var script = document.createElement('script');

    script.setAttribute('src', 'http://spreadsheets.google.com/feeds/list'
                         + '/' + param_styleSheetKey + '/' + worksheet_number + '/public/values' +
                        '?alt=json-in-script&callback=loadMapJSON');
    script.setAttribute('id', 'jsonScript');
    script.setAttribute('type', 'text/javascript');
    document.documentElement.firstChild.appendChild(script);
    ////// End G O O G L E   C O D E //////////
}

//////////////////////////   NON Google Map related Code ///////////////////////////////////////////////////

var win = null;
//Function to show the comparison window with the comprison calendar 
//@pos - position of the marker in which the compare button was clicked
function compareWindow(position_of_marker){
	// create the window on the first click and reuse on subsequent clicks
	if(!win){
		// create the modal window.
		win = new Ext.Window({
			el:'compare-schedules',
			title : 'Compare Schedules',
			layout:'fit',
			width:820,
			height:500,
			closeAction:'hide',
			plain: true,
			html:'<div id="comparison_element"></div>',
			modal : true,
			shadow:true,
			waitMsgTarget : true
		});
	}
    //Add a function to the show event of window
	win.addListener("show",function(){
		var iframe = Ext.get("comparison_element");
		
		// delete the last comparison calendar if any
		iframe.dom.innerHTML="";
    	
    	// read the compare code from the array.
		var comparison_string = comparisons[position_of_marker];
        // Check if the comprison string was provided in the worksheet for this marker.
        if(comparison_string.trim()!=""){   
		    // set the string so that it pulls the google comprison calendar 
		    iframe.dom.innerHTML = comparison_string;
		}else{
            // If not found then show the message so that it can be provided.
		    iframe.dom.innerHTML = "<H1>NO COMPARISON PROVIDED!</h1>"
		}
	});
	
	// show the window
	win.show(this);

};


// resize the map containing div when the browser window gets resized.
function resizeApp() {
    var offsetTop = 0;
    var mapElem = document.getElementById("map");
    for (var elem = mapElem; elem; elem = elem.offsetParent) {
        offsetTop += elem.offsetTop;
    }
    // calculate the height available.
    var height = getWindowHeight() - offsetTop;// - 10 if we want to leave some space at bottom
    if (height >= 0) {
        //mapElem.style.height = height + "px";
    }
    if(map){
        // tell the map object about the resize 
        map.checkResize();
    }    
};
// calculates the height of the browser window.
function getWindowHeight() {
    if (window.self && self.innerHeight) {
        return self.innerHeight;}
    if (document.documentElement && document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    }
    return 0;
}
// this is how load function gets called when the page is loaded in browser.
setTimeout('load()', 500); 

//]]>
</script>
<!-- This html is for the comprison window -->
<div id="compare-schedules" class="x-hidden">
    <div class="x-window-header">&#160;</div>
    <div id="compare-schedules-content">
        
    </div>
</div>


</body>

</html>
